#include "myfile.h"

_FILE* _fopen(const char* filename,const char*flag)
{
    assert(filename);
    assert(flag);

    int fd = -1;
    if(strcmp(flag,"a") == 0)
    {
        fd = open(filename,O_CREAT | O_WRONLY | O_APPEND,0666);
    }
    else if(strcmp(flag,"w") == 0)
    {
        fd = open(filename,O_CREAT | O_WRONLY | O_TRUNC,0666);
    }
    else if(strcmp(flag,"r") == 0)
    {
        fd = open(filename,O_RDONLY);
    }
    else 
        return NULL;

    if(fd == -1)
        return NULL;

    _FILE* fp = (_FILE*)malloc(sizeof(_FILE));
    if(fp == NULL)
        return NULL;
    
    fp->fileno = fd;
    fp->flag = FLUSH_LINK;
    fp->out_pos = 0;

    return fp;
}
int _fwrite(_FILE* fp,const char* str,int size)
{
    memcpy(&fp->out_buffer[fp->out_pos],str,size);
    fp->out_pos += size;

    if(fp->flag & FLUSH_NOW)
    {
        write(fp->fileno,fp->out_buffer,fp->out_pos);
        fp->out_pos = 0;
    }
    else if(fp->flag & FLUSH_LINK)
    {
        if(fp->out_buffer[fp->out_pos-1] == '\n')
        {
            write(fp->fileno,fp->out_buffer,fp->out_pos);
            fp->out_pos = 0;
        }
    }
    else if(fp->flag & FLUSH_ALL)
    {
        if(fp->out_pos == SIZE)
        {
            write(fp->fileno,fp->out_buffer,fp->out_pos);
            fp->out_pos = 0;
        }
    }

    return size;
}
void _ffulsh(_FILE* fp)
{
    if(fp->out_pos > 0)
    {
        write(fp->fileno,fp->out_buffer,fp->out_pos);
        fp->out_pos = 0;
    }
}
void _fclose(_FILE* fp)
{
    if(fp == NULL)
        return;
    _ffulsh(fp);
    close(fp->fileno);
    free(fp);
}
